import React, { useEffect, useState } from 'react';
import {
    ActivityIndicator,
    StyleProp,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    ViewStyle
} from 'react-native';

import { useTestResults } from "@/contexts/TestResultsContext";
import BluetoothService from "@/utils/BluetoothService";
// 移除对CardiovascularParser的直接导入，让子组件通过props提供解析逻辑
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Device } from "react-native-ble-plx";

export type MeasurementValue = number | string | { [key: string]: number | string };

export type MeasurementData = {
    value: MeasurementValue;
    unit: string | { [key: string]: string };
    rawData: string;
    timestamp: string;
};

type DeviceParser = {
    parseData: (hexString: string) => MeasurementData | null | void;
    // 可选：带元信息的解析（用于多特征订阅场景）
    parseDataWithMeta?: (hexString: string, meta: { characteristicUUID: string }) => MeasurementData | null | void;
};

type DeviceTemplateProps = {
    deviceName: string;
    deviceNamePrefix: string[] | string;
    serviceUUID: string;
    dataCharacteristic: string;
    // 可选：多个上报特征（如血压/心率血氧/心电分开上报）
    dataCharacteristics?: string[];
    commandServiceUUID: string | undefined;
    commandCharacteristic: string | undefined;
    initCommands?: string[];
    startCommand: string;
    stopCommand: string;
    withResp: boolean;
    parser: DeviceParser;
    children?: React.ReactNode;
    deviceRoute?: string; // 添加设备路由参数
    // 可选：自定义订阅逻辑，用于设备特定的数据订阅处理
    customSubscribeToData?: () => Promise<void>;
    // 可选：自定义结果渲染逻辑，用于设备特定的UI展示
    customRenderResult?: () => React.ReactNode;
    // 可选：检测完成回调
    onTestComplete?: () => void;
};

// 模块级变量，用于立即防止重复触发回调
let dynamometerCallbackTriggered = false;
let vitalCapacityCallbackTriggered = false;
let vitalCapacityFinalValue: number | null = null; // 存储肺活量的最终值

const DeviceTemplate: React.FC<DeviceTemplateProps> = ({
                                                           deviceName,
                                                           serviceUUID,
                                                           commandServiceUUID,
                                                           dataCharacteristic,
                                                           dataCharacteristics,
                                                           commandCharacteristic,
                                                           parser,
                                                           deviceNamePrefix,
                                                           startCommand,
                                                           initCommands,
                                                           stopCommand,
                                                           withResp,
                                                           children,
                                                           deviceRoute,
                                                           customSubscribeToData,
                                                           customRenderResult,
                                                           onTestComplete
                                                       }) => {
    const [isConnected, setIsConnected] = useState<boolean>(false);
    const [isMeasuring, setIsMeasuring] = useState<boolean>(false);
    const [measurement, setMeasurement] = useState<MeasurementData | null | void>(null);
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [isAutoConnecting, setIsAutoConnecting] = useState<boolean>(false); // 自动连接状态
    const [lastUpdateTime, setLastUpdateTime] = useState<number>(0);
    const [autoSaveEnabled, setAutoSaveEnabled] = useState<boolean>(true); // 自动保存开关
    const [showCompletionDialog, setShowCompletionDialog] = useState(false); // 检测完成提示对话框状态
    const throttleInterval = 300; // 300ms节流间隔，降低以确保更多数据点
    const [baselineValues, setBaselineValues] = useState<any>(null);
    const [hasTriggeredCallback, setHasTriggeredCallback] = useState(false); // 是否已经触发过回调

    const {addTestResult} = useTestResults();



    // 加载用户基准值
    useEffect(() => {
        const loadBaselineValues = async () => {
            try {
                const baselineStr = await AsyncStorage.getItem('USER_BASELINE');
                if (baselineStr) {
                    setBaselineValues(JSON.parse(baselineStr));
                } else {
                    // 默认基准值
                    setBaselineValues({
                        heartRate: 75,
                        bloodPressureLow: 80,
                        bloodPressureHigh: 120,
                        reactionTime: 500,
                        gripStrength: 40,
                        vitalCapacity: 3500
                    });
                }
            } catch (error) {
                console.error('加载基准值失败:', error);
            }
        };

        loadBaselineValues();
    }, []);

    // 原子方法 - 查找设备
    const findDevice = async (prefix: string[] | string): Promise<Device> => {
        if (!BluetoothService.isReady()) {
            throw new Error('蓝牙服务尚未初始化，请稍后再试');
        }

        const device = await BluetoothService.findDeviceByNamePrefix(
            null,
            prefix
        );
        if (!device) {
            throw new Error(`设备查找失败: 未找到名称以${prefix}开头的设备`);
        }
        return device;
    };

    // 原子方法 - 连接设备
    const connect = async (device: Device): Promise<void> => {
        if (!BluetoothService.isReady()) {
            throw new Error('蓝牙服务尚未初始化，请稍后再试');
        }

        const connectionOptions = {
            autoConnect: false,
            connectionPriority: 1,
            shouldEnableNotificationWhenServiceDiscovered: true
        };
        try {
            await BluetoothService.connectDevice(
                device.id,
                [serviceUUID],
                connectionOptions
            );
            setIsConnected(true);
            await new Promise(resolve => setTimeout(resolve, 100));
            if (initCommands) {
                await sendInitCommands();
            }
        } catch (err) {
            throw new Error(`连接失败: ${err}`);
        }
    };

    const subscribeToData = async (): Promise<void> => {
        if (!BluetoothService.isReady()) {
            throw new Error('蓝牙服务尚未初始化，请稍后再试');
        }

        // 如果提供了自定义订阅逻辑，则使用自定义逻辑
        if (customSubscribeToData) {
            await customSubscribeToData();
            return;
        }

        // 通用订阅逻辑，适用于大多数设备
        const targets = (dataCharacteristics && dataCharacteristics.length > 0)
            ? dataCharacteristics
            : [dataCharacteristic];

        for (const characteristic of targets) {
            await BluetoothService.addNotifyRequest(
                serviceUUID,
                characteristic,
                (data: string) => {
                    try {
                        const currentTime = Date.now();
                        const timeDiff = currentTime - lastUpdateTime;
                        if (timeDiff >= throttleInterval) {
                            const parsed = parser.parseDataWithMeta
                                ? parser.parseDataWithMeta(data, {characteristicUUID: characteristic})
                                : parser.parseData(data);
                            if (parsed) {
                                setMeasurement(parsed);
                                setLastUpdateTime(currentTime);
                                
                                console.log('设备类型:', deviceRoute, '解析结果:', parsed, '时间间隔:', timeDiff + 'ms');
                                
                                // 对于不同设备类型的检测完成判断
                                if (deviceRoute && ['Dynamometer', 'VitalCapacity', 'Alcohol'].includes(deviceRoute)) {
                                    // 酒精检测特殊处理：接收到酒精值就立即弹框
                                    if (deviceRoute === 'Alcohol') {
                                        // 检查是否已经触发过回调，防止重复触发
                                        if (hasTriggeredCallback) {
                                            console.log(`设备类型: ${deviceRoute}, 已触发过回调，忽略当前值: ${parsed.value}`);
                                            return;
                                        }
                                        
                                        // 只要接收到酒精浓度值就弹框（包括0值）
                                        if (parsed && parsed.value !== undefined && parsed.value !== null && 
                                            typeof parsed.value === 'number' && parsed.isTested) {
                                            // 检查是否已经触发过回调，防止重复触发
                                            if (hasTriggeredCallback) {
                                                console.log(`设备类型: ${deviceRoute}, 已触发过回调，忽略当前值: ${parsed.value}`);
                                                return;
                                            }
                                            
                                            console.log('酒精检测接收到有效值:', parsed.value, '是否正在测量:', isMeasuring, '回调函数:', !!onTestComplete);
                                            setHasTriggeredCallback(true);
                                            
                                            // 对于酒精检测，即使 isMeasuring 为 false，只要有已测试的值也触发回调
                                            // 因为酒精检测可能因为接收到最终结果而自动停止测量
                                            if (onTestComplete) {
                                                console.log('调用酒精检测完成回调');
                                                onTestComplete();
                                            }
                                        } else {
                                            console.log('未触发酒精检测完成，原因:', !parsed ? '没有解析结果' : '不是有效的酒精浓度值或未标记为已测试');
                                        }
                                    } else {
                                        // 对于握力设备，优先使用报文中的完成标志位判断
                                        if (deviceRoute === 'Dynamometer') {
                                            // 检查是否已经触发过回调，防止重复触发
                                            if (hasTriggeredCallback) {
                                                console.log(`设备类型: ${deviceRoute}, 已触发过回调，忽略当前值`);
                                                return;
                                            }
                                            
                                            // 检查报文中的完成标志位
                                            if (parsed && parsed.isComplete === true) {
                                                let numericValue = parsed.value;
                                                if (typeof numericValue === 'string') {
                                                    numericValue = parseFloat(numericValue);
                                                }
                                                
                                            // 如果检测完成标志为true且握力值大于5kg，认为有效测量
                                            if (!isNaN(numericValue) && numericValue > 5) {
                                                // 使用模块级变量立即防止重复触发
                                                if (dynamometerCallbackTriggered) {
                                                    console.log(`设备类型: ${deviceRoute}, 回调已触发，忽略当前值: ${numericValue}`);
                                                    return;
                                                }
                                                
                                                console.log('握力检测报文标志显示检测完成(报文位1)，握力值:', numericValue, '触发完成回调');
                                                
                                                // 立即设置模块级标志，防止重复触发
                                                dynamometerCallbackTriggered = true;
                                                setHasTriggeredCallback(true);
                                                
                                                if (onTestComplete) {
                                                    onTestComplete();
                                                }
                                            } else {
                                                console.log('握力检测完成标志为true但握力值过小，不视为有效测量');
                                            }
                                            } else {
                                                // 如果报文标志位未显示完成，继续等待
                                                let numericValue = parsed.value;
                                                if (typeof numericValue === 'string') {
                                                    numericValue = parseFloat(numericValue);
                                                }
                                                
                                                console.log(`设备类型: ${deviceRoute}, 当前值: ${numericValue}，等待检测完成标志`);
                                            }
                                        } else if (deviceRoute === 'VitalCapacity') {
                                            // 对于肺活量设备，优先使用报文中的完成标志位判断
                                            let numericValue = parsed.value;
                                            if (typeof numericValue === 'string') {
                                                numericValue = parseFloat(numericValue);
                                            }
                                            
                                            // 检查是否已经触发过回调，防止重复触发
                                            if (hasTriggeredCallback) {
                                                console.log(`设备类型: ${deviceRoute}, 已触发过回调，忽略当前值: ${numericValue}`);
                                                return;
                                            }
                                            
                                            // 检查报文中的完成标志位
                                            if (parsed && parsed.isComplete === true) {
                                                // 存储最终的肺活量值
                                                if (typeof numericValue === 'number' && !isNaN(numericValue)) {
                                                    vitalCapacityFinalValue = numericValue;
                                                }
                                                
                                                // 使用模块级变量立即防止重复触发
                                                if (vitalCapacityCallbackTriggered) {
                                                    console.log(`设备类型: ${deviceRoute}, 回调已触发，忽略当前值: ${numericValue}`);
                                                    return;
                                                }
                                                
                                                // 如果检测完成标志为true且肺活量值大于1000ml，认为有效测量
                                                if (vitalCapacityFinalValue !== null && vitalCapacityFinalValue > 1000) {
                                                    console.log('肺活量检测报文标志显示检测完成(报文位1)，肺活量值:', vitalCapacityFinalValue, '触发完成回调');
                                                    
                                                    // 立即设置模块级标志，防止重复触发
                                                    vitalCapacityCallbackTriggered = true;
                                                    setHasTriggeredCallback(true);
                                                    
                                                    if (onTestComplete) {
                                                        onTestComplete();
                                                    }
                                                } else {
                                                    console.log('肺活量检测完成标志为true但肺活量值过小，不视为有效测量');
                                                }
                                            } else {
                                                // 如果报文标志位未显示完成，继续等待
                                                console.log(`设备类型: ${deviceRoute}, 当前值: ${numericValue}，等待检测完成标志`);
                                            }
                                        } else {
                                            // 其他设备暂时不处理完成逻辑
                                            console.log(`设备类型: ${deviceRoute}, 当前值: ${parsed.value}`);
                                        }
                                    }
                                }
                                
                                if (autoSaveEnabled && deviceRoute) {
                                    addTestResult(deviceRoute, deviceName, parsed);
                                }
                            }
                        } else {
                            console.log('数据被节流跳过，时间间隔:', timeDiff + 'ms');
                        }
                    } catch (e) {
                        console.log(`数据解析错误: ${e}`);
                    }
                }
            );
        }
    };

    // 原子方法 - 发送初始化命令
    const sendInitCommands = async (): Promise<void> => {
        console.log('发送初始化命令')
        console.log(commandServiceUUID, commandCharacteristic, initCommands)
        if (initCommands && commandServiceUUID && commandCharacteristic) {
            for (const cmd of initCommands) {
                await BluetoothService.writeCommand(
                    commandServiceUUID,
                    commandCharacteristic,
                    cmd
                );
            }
        }
    };

    // 组合方法 - 完整连接流程
    const connectDevice = async (prefix: string[] | string, isAutoConnect: boolean = false): Promise<void> => {
        // 创建一个AbortController来控制异步操作
        const abortController = new AbortController();
        return connectDeviceWithAbort(prefix, isAutoConnect, abortController);
    };

    // 带有取消控制的连接方法
    const connectDeviceWithAbort = async (
        prefix: string[] | string, 
        isAutoConnect: boolean = false, 
        abortController?: AbortController
    ): Promise<void> => {
        // 如果没有传入abortController，使用全局的
        if (!abortController) {
            abortController = (global as any).deviceTemplateAbortController;
        }
        
        // 如果仍然没有abortController，创建一个新的
        if (!abortController) {
            abortController = new AbortController();
        }

        // 如果已经连接，直接返回
        if (isConnected) {
            console.log('设备已连接，跳过连接流程');
            return;
        }

        let retryCount = 0;
        const maxRetries = isAutoConnect ? 30 : 3; // 自动连接时只尝试30次

        // 手动连接时显示加载状态
        if (!isAutoConnect) {
            setIsLoading(true);
        }

        while (retryCount < maxRetries) {
            try {
                console.log(`尝试连接设备 (第${retryCount + 1}次)...`);

                // 检查是否已取消
                if (abortController.signal.aborted) {
                    console.log('连接操作已取消');
                    return;
                }

                const device = await findDevice(prefix);
                
                // 在连接前再次检查是否已取消
                if (abortController.signal.aborted) {
                    console.log('组件已卸载，停止连接尝试');
                    return;
                }
                
                await connect(device);

                console.log('设备连接成功');
                // 连接成功后清除错误信息
                return;

            } catch (err) {
                // 检查是否已取消
                if (abortController.signal.aborted) {
                    console.log('组件已卸载，停止连接尝试');
                    return;
                }
                
                retryCount++;
                const errorMessage = err instanceof Error ? err.message : String(err);
                console.log(`连接尝试 ${retryCount} 失败:`, errorMessage);

                if (retryCount >= maxRetries) {
                    console.log('连接最终失败');
                } else {
                    // 重试前等待，但也要检查是否已取消
                    await new Promise<void>((resolve) => {
                        const checkAbort = () => {
                            if (abortController.signal.aborted) {
                                console.log('等待期间组件已卸载，停止连接尝试');
                                return;
                            }
                            resolve();
                        };
                        
                        setTimeout(checkAbort, isAutoConnect ? 3000 : 1000);
                    });
                }
            }
        }

        // 最终清理加载状态
        if (!isAutoConnect) {
            setIsLoading(false);
        }
    };

    // 断开设备
    const disconnectDevice = async () => {
        try {
            setIsLoading(true);
            await BluetoothService.removeAllNotifyRequests();
            await BluetoothService.disconnectDevice();
            setIsConnected(false);
            setIsMeasuring(false);
            setMeasurement(null);
        } catch (err) {
            console.error(`断开连接失败: ${err}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 开始测量
    const startMeasurement = async () => {
        if (!isConnected) return;

        try {
            setIsLoading(true);
            
            // 重置回调状态
            setHasTriggeredCallback(false);
            dynamometerCallbackTriggered = false; // 重置模块级变量
            vitalCapacityCallbackTriggered = false; // 重置肺活量模块级变量
            vitalCapacityFinalValue = null; // 重置肺活量最终值
            
            await subscribeToData();
            if (commandServiceUUID && commandCharacteristic) {
                await BluetoothService.writeCommand(
                    commandServiceUUID,
                    commandCharacteristic,
                    startCommand,
                    withResp
                );
            }
            setIsMeasuring(true);
        } catch (err) {
            console.error(`开始测量失败: ${err}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 停止测量
    const stopMeasurement = async () => {
        if (!isConnected) return;

        try {
            setIsLoading(true);
            const command = stopCommand;
            if (commandServiceUUID && commandCharacteristic) {
                await BluetoothService.writeCommand(
                    commandServiceUUID,
                    commandCharacteristic,
                    command
                );
            }
            setIsMeasuring(false);

            // 保存测试结果到上下文
            if (measurement && deviceRoute) {
                addTestResult(deviceRoute, deviceName, measurement);
            }
        } catch (err) {
            console.error(`停止测量失败: ${err}`);
        } finally {
            setIsLoading(false);
        }
    };

    // 提交未测试状态（仅用于酒精测试）
    const submitUntestedResult = () => {
        if (!deviceRoute || deviceRoute !== 'Alcohol') return;
        
        // 创建一个未测试的测量结果
        const untestedResult = {
            value: 0,
            unit: 'mg/100ml',
            rawData: '',
            timestamp: new Date().toISOString(),
            isTested: false
        };
        
        addTestResult(deviceRoute, deviceName, untestedResult);
    };

    // 重置肺活量检测状态
    const resetVitalCapacityState = () => {
        vitalCapacityCallbackTriggered = false;
        vitalCapacityFinalValue = null;
    };

    // 组件挂载时自动连接设备
    useEffect(() => {
        let isMounted = true;
        let autoConnectTimeout: ReturnType<typeof setTimeout>;
        let abortController: AbortController;

        const performAutoConnect = async () => {
            try {
                // 检查组件是否仍然挂载且未连接
                if (!isMounted || isConnected) {
                    return;
                }

                // 检查蓝牙服务是否准备就绪
                if (!BluetoothService.isReady()) {
                    console.log('蓝牙服务未准备就绪，跳过自动连接');
                    return;
                }

                console.log('开始自动连接设备:', deviceNamePrefix);
                setIsAutoConnecting(true); // 设置自动连接状态
                
                // 创建新的AbortController用于控制连接操作
                abortController = new AbortController();
                
                // 修改connectDevice函数调用，传入abortController
                await connectDeviceWithAbort(deviceNamePrefix, true, abortController);
            } catch (err) {
                console.log('自动连接失败:', err);
                // 自动连接失败不显示错误，用户可以手动连接
            } finally {
                if (isMounted) {
                    setIsAutoConnecting(false); // 清除自动连接状态
                }
            }
        };

        // 延迟执行自动连接，确保组件完全挂载和蓝牙服务初始化
        autoConnectTimeout = setTimeout(performAutoConnect, 1500);

        return () => {
            isMounted = false;
            if (autoConnectTimeout) {
                clearTimeout(autoConnectTimeout);
            }
            // 组件卸载时，取消所有进行中的连接操作
            if (abortController) {
                abortController.abort();
            }
            // 确保清理自动连接状态
            setIsAutoConnecting(false);
        };
    }, [deviceNamePrefix]); // 依赖设备名称前缀

    // 蓝牙状态监听
    useEffect(() => {
        let isMounted = true;
        
        const stateSubscription = BluetoothService.addStateListener((state) => {
            if (!isMounted) return; // 如果组件已卸载，不处理状态变化
            
            if (state === 'PoweredOff') {
                console.error('蓝牙已关闭，请打开蓝牙后重试');
                setIsConnected(false);
                setIsMeasuring(false);
            }
        });

        return () => {
            isMounted = false;
            if (stateSubscription) {
                stateSubscription.remove();
            }
        };
    }, []);

    // 连接状态检查
    useEffect(() => {
        let isMounted = true;
        let checkInterval: ReturnType<typeof setInterval>;

        if (isConnected) {
            checkInterval = setInterval(() => {
                // 如果组件已卸载，不执行检查
                if (!isMounted) return;
                
                // 这里可以添加更精确的连接状态检查逻辑
                // 例如尝试读取某个特性值来验证连接是否仍然活跃
            }, 5000);
        }

        return () => {
            isMounted = false;
            if (checkInterval) {
                clearInterval(checkInterval);
            }
        };
    }, [isConnected]);

    // 组件卸载时的清理
    useEffect(() => {
        let isMounted = true;
        let abortController: AbortController;
        
        // 创建一个全局的AbortController，用于在组件卸载时取消所有操作
        abortController = new AbortController();
        
        // 将abortController暴露给全局，以便其他函数可以使用
        (global as any).deviceTemplateAbortController = abortController;
        
        return () => {
            isMounted = false;
            const cleanup = async () => {
                try {
                    console.log('组件卸载，清理蓝牙连接');
                    // 取消所有进行中的操作
                    abortController.abort();
                    
                    // 停止测量
                    setIsMeasuring(false);
                    
                    // 移除所有通知请求
                    await BluetoothService.removeAllNotifyRequests();

                    // 断开设备连接
                    await BluetoothService.disconnectDevice();
                    
                    // 重置连接状态
                    setIsConnected(false);
                } catch (err) {
                    console.log('清理连接时出错:', err);
                }
            };

            cleanup();
        };
    }, []); // 空依赖数组，只在组件卸载时执行

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <Text style={styles.title}>{deviceName}</Text>
                <Text style={styles.subtitle}>请按照提示进行测量</Text>
            </View>

            <View style={styles.content}>
                <View style={styles.statusContainer}>
                    <View style={styles.statusInfo}>
                        <View style={[
                            styles.statusIndicator,
                            {backgroundColor: isConnected ? '#4CAF50' : '#F44336'} as StyleProp<ViewStyle>
                        ]}/>
                        <Text style={styles.statusText}>
                            {isConnected ? '已连接' : '未连接'}
                        </Text>
                        {autoSaveEnabled && (
                            <Text style={styles.autoSaveText}>
                                (自动保存)
                            </Text>
                        )}
                    </View>

                    {!isConnected && (
                        <TouchableOpacity
                            style={[
                                styles.connectButton,
                                (isLoading || isAutoConnecting) && styles.disabledConnectButton
                            ]}
                            onPress={() => {
                                // 创建一个新的AbortController用于手动连接
                                const manualAbortController = new AbortController();
                                connectDeviceWithAbort(deviceNamePrefix, false, manualAbortController);
                            }}
                            disabled={isLoading || isAutoConnecting}
                        >
                            {(isLoading || isAutoConnecting) ? (
                                <View className="flex flex-row items-center">
                                    <Text className="text-white mr-2">自动连接中 </Text>
                                    <ActivityIndicator color="#FFFFFF" size={12}/>
                                </View>
                            ) : (
                                <Text style={styles.connectButtonText}>
                                    {isAutoConnecting ? '自动连接中...' : '连接设备'}
                                </Text>
                            )}
                        </TouchableOpacity>
                    )}
                </View>

                <View style={styles.dataContainer}>
                    <View style={styles.contentLayout}>
                        <View style={styles.guideSection}>
                            <Text style={styles.guideSectionTitle}>操作流程指引</Text>
                            <View style={styles.guideContent}>
                                {/* 这里放置操作指引内容 */}
                                {React.Children.map(children, child => {
                                    // @ts-ignore
                                    if (React.isValidElement(child) && child.props?.type === 'guideText') {
                                        return child;
                                    }
                                    return null;
                                })}
                            </View>
                        </View>

                        <View style={styles.demoSection}>
                            {/* 视频演示部分 */}
                            {React.Children.map(children, child => {
                                // @ts-ignore
                                if (React.isValidElement(child) && child.props?.type !== 'guideText') {
                                    return child;
                                }
                                return null;
                            })}

                            {/* 开始检测按钮 - 始终显示但在未连接时禁用 */}
                            <TouchableOpacity
                                style={[styles.startButton, !isConnected && styles.disabledButton]}
                                onPress={!isMeasuring ? startMeasurement : stopMeasurement}
                                disabled={!isConnected || isLoading}
                            >
                                {isLoading ? (
                                    <ActivityIndicator color="#FFFFFF"/>
                                ) : (
                                    <Text style={styles.buttonText}>
                                        {!isMeasuring ? '开始检测' : '停止检测'}
                                    </Text>
                                )}
                            </TouchableOpacity>
                        </View>
                    </View>

                    {(customRenderResult || !!measurement) && (
                        <View style={styles.resultContainer}>
                            {customRenderResult ? customRenderResult() : (() => {
                                const isObjectValue = measurement && typeof measurement.value === 'object' && !Array.isArray(measurement.value);
                                
                                // 默认结果渲染
                                return (
                                    <>
                                        {isObjectValue && measurement ? (
                                            Object.entries(measurement.value as { [key: string]: number | string }).map(([key, val]) => (
                                                <Text key={key} style={styles.resultText}>
                                                    {key}: {val} {typeof measurement.unit === 'object' ? (measurement.unit as any)[key] : measurement.unit}
                                                </Text>
                                            ))
                                        ) : (
                                            measurement ? (
                                                <Text style={styles.resultText}>
                                                    {'' + measurement.value + measurement.unit}
                                                </Text>
                                            ) : null
                                        )}
                                    </>
                                );
                            })()}

                            {/*<View style={styles.saveButtonContainer}>*/}
                            {/*    <TouchableOpacity*/}
                            {/*        style={styles.saveButton}*/}
                            {/*        onPress={() => {*/}
                            {/*            if (measurement && deviceRoute) {*/}
                            {/*                addTestResult(deviceRoute, deviceName, measurement);*/}
                            {/*            }*/}
                            {/*        }}*/}
                            {/*    >*/}
                            {/*        <Text style={styles.saveButtonText}>手动保存</Text>*/}
                            {/*    </TouchableOpacity>*/}
                            {/*    {deviceRoute === 'Alcohol' && (*/}
                            {/*        <TouchableOpacity*/}
                            {/*            style={[styles.saveButton, styles.untestedButton]}*/}
                            {/*            onPress={submitUntestedResult}*/}
                            {/*        >*/}
                            {/*            <Text style={styles.saveButtonText}>提交未测试</Text>*/}
                            {/*        </TouchableOpacity>*/}
                            {/*    )}*/}
                            {/*    <TouchableOpacity*/}
                            {/*        style={[styles.saveButton, autoSaveEnabled ? styles.autoSaveOn : styles.autoSaveOff]}*/}
                            {/*        onPress={() => setAutoSaveEnabled(!autoSaveEnabled)}*/}
                            {/*    >*/}
                            {/*        <Text style={styles.saveButtonText}>*/}
                            {/*            自动保存: {autoSaveEnabled ? '开' : '关'}*/}
                            {/*        </Text>*/}
                            {/*    </TouchableOpacity>*/}
                            {/*</View>*/}
                        </View>
                    )}
                </View>
            </View>
            
            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                        <View style={styles.dialogButtons}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.stayButton]}
                                onPress={() => setShowCompletionDialog(false)}
                            >
                                <Text style={styles.returnButtonText}>返回</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.returnButton]}
                                onPress={() => setShowCompletionDialog(false)}
                            >
                                <Text style={styles.stayButtonText}>继续检测</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f6f8fa',
    },
    header: {
        backgroundColor: '#0a7ea4',
        paddingTop: 20,
        paddingBottom: 20,
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        color: 'white',
        marginBottom: 8,
    },
    subtitle: {
        fontSize: 16,
        color: 'rgba(255,255,255,0.9)',
        textAlign: 'center',
    },
    content: {
        flex: 1,
        padding: 20,
    },
    statusContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,
        backgroundColor: 'white',
        padding: 12,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    statusInfo: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    statusIndicator: {
        width: 12,
        height: 12,
        borderRadius: 6,
        marginRight: 8,
    },
    statusText: {
        fontSize: 16,
        color: '#333',
    },
    autoSaveText: {
        fontSize: 12,
        color: '#4CAF50',
        marginLeft: 8,
    },
    connectButton: {
        backgroundColor: '#0a7ea4',
        paddingVertical: 8,
        paddingHorizontal: 16,
        borderRadius: 6,
        alignItems: 'center',
    },
    disabledConnectButton: {
        backgroundColor: '#B0BEC5',
        opacity: 0.6,
    },
    connectButtonText: {
        alignItems: 'center',
        color: '#FFFFFF',
        fontSize: 14,
        fontWeight: 'bold',
    },
    errorContainer: {
        marginBottom: 20,
        padding: 15,
        backgroundColor: '#FFEBEE',
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    errorText: {
        color: '#F44336',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    errorDetails: {
        color: '#F44336',
        fontSize: 12,
        marginTop: 5,
        textAlign: 'left',
    },
    dataContainer: {
        flex: 1,
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 20,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    contentLayout: {
        flexDirection: 'row',
        flex: 1,
    },
    guideSection: {
        flex: 1,
        paddingRight: 15,
        borderRightWidth: 1,
        borderRightColor: '#eaeaea',
    },
    guideSectionTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 15,
    },
    guideContent: {
        flex: 1,
    },
    demoSection: {
        flex: 1,
        paddingLeft: 15,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column',
    },
    startButton: {
        backgroundColor: '#4CAF50',
        padding: 15,
        borderRadius: 8,
        alignItems: 'center',
        width: '100%',
        marginTop: 15,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    disabledButton: {
        backgroundColor: '#A5D6A7', // 浅绿色，表示禁用状态
        opacity: 0.6,
    },
    resultContainer: {
        marginTop: 20,
        alignItems: 'center',
    },
    resultText: {
        fontSize: 32,
        fontWeight: 'bold',
        color: '#0a7ea4',
        textAlign: 'center',
    },
    dataGrid: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        gap: 10,
        marginBottom: 8,
    },
    dataCard: {
        flex: 1,
        backgroundColor: '#f8f9fa',
        borderRadius: 8,
        padding: 12,
        alignItems: 'center',
        justifyContent: 'center',
        borderWidth: 1,
        borderColor: '#e0e0e0',
    },
    dataLabel: {
        fontSize: 14,
        color: '#666',
        marginBottom: 6,
    },
    dataValue: {
        fontSize: 28,
        fontWeight: 'bold',
        color: '#0a7ea4',
    },
    unitSmall: {
        fontSize: 14,
        color: '#0a7ea4',
        marginLeft: 4,
    },
    cuffText: {
        marginTop: 6,
        fontSize: 12,
        color: '#333',
    },
    judgmentScoreText: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#4CAF50',
        textAlign: 'center',
        marginTop: 5,
    },
    saveButtonContainer: {
        flexDirection: 'row',
        marginTop: 10,
        gap: 10,
    },
    buttonContainer: {
        marginTop: 20,
    },
    button: {
        backgroundColor: '#0a7ea4',
        padding: 15,
        borderRadius: 8,
        alignItems: 'center',
        marginBottom: 10,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    disconnectButton: {
        backgroundColor: '#F44336',
    },
    buttonText: {
        color: '#FFFFFF',
        fontSize: 16,
        fontWeight: 'bold',
    },
    saveButton: {
        backgroundColor: '#4CAF50',
        padding: 10,
        borderRadius: 8,
        alignItems: 'center',
        flex: 1,
    },
    untestedButton: {
        backgroundColor: '#9E9E9E',
    },
    autoSaveOn: {
        backgroundColor: '#4CAF50',
    },
    autoSaveOff: {
        backgroundColor: '#9E9E9E',
    },
    saveButtonText: {
        color: '#FFFFFF',
        fontSize: 14,
        fontWeight: 'bold',
    },
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
})
export default DeviceTemplate;